/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.carbs.harmony.avatarimageview.example.adapter;

import cn.carbs.harmony.avatarimageview.example.ResourceTable;
import cn.carbs.harmony.avatarimageview.library.AvatarImageView;
import cn.carbs.harmony.avatarimageview.example.model.Model;

import com.bumptech.glide.Glide;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.app.Context;

import java.util.List;

public class ModelBaseAdapter extends BaseItemProvider {

    private Context context;
    private List<Model> Modeles;


    public ModelBaseAdapter(Context context, List<Model> Modeles) {
        this.context = context;
        this.Modeles = Modeles;
    }

    @Override
    public int getCount() {
        return Modeles.size();
    }

    @Override
    public Object getItem(int i)
    {
        return Modeles.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        Model model = Modeles.get(i);
        Text itemName;
        AvatarImageView itemAvatar;
        Component container = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_hero, null, false);
        itemAvatar = (AvatarImageView) container.findComponentById(ResourceTable.Id_item_avatar);
        itemName = (Text) container.findComponentById(ResourceTable.Id_item_name);
        itemName.setText(model.text);
        refreshAvatarImageView(itemAvatar,model);
        return container;
    }

    private void refreshAvatarImageView(AvatarImageView aiv, Model model){
        if(aiv == null){
            return;
        }

        Glide.with(context)
                .load(model.url)
                .circleCrop()
                .into(aiv);
    }
}
